package com.hbzhit.common.validator;

import cn.hutool.core.util.StrUtil;
import com.hbzhit.common.exception.RRException;

import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import java.util.Collection;
import java.util.Set;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * hibernate-validator校验工具类
 * 参考文档：http://docs.jboss.org/hibernate/validator/5.4/reference/en-US/html_single/
 * @author DING
 * @date 2021/4/9 17:33
 * @version 1.0
 **/
public class ValidatorUtils {
    private static final Validator VALIDATOR;

    static {
        VALIDATOR = Validation.buildDefaultValidatorFactory().getValidator();
    }

    /**
     * 校验对象
     * @param object        待校验对象
     * @param groups        待校验的组
     * @throws RRException  校验不通过，则报ResException异常
     */
    public static void validateEntity(Object object, Class<?>... groups) {
        String msg = ValidatorUtils.validate(object, groups);
        if (msg != null) {
            throw new RRException(msg);
        }
    }

    /**
     * 校验集合
     * @param objects        待校验集合
     * @param groups        待校验的组
     * @throws RRException  校验不通过，则报ResException异常
     */
    public static void validateEntityList(Collection<?> objects, Class<?>... groups) {
        AtomicInteger row = new AtomicInteger(1);
        objects.forEach(obj -> {
            String msg = ValidatorUtils.validate(obj, groups);
            if (msg != null) {
                throw new RRException(StrUtil.format("第{}行：{}", row.getAndIncrement(), msg));
            }
        });
    }

    public static String validate(Object object, Class<?>... groups) {
        StringBuilder msg = new StringBuilder();
        Set<ConstraintViolation<Object>> constraintViolations = VALIDATOR.validate(object, groups);
        if (!constraintViolations.isEmpty()) {
            for(ConstraintViolation<Object> constraint:  constraintViolations){
                msg.append(constraint.getMessage()).append(";");
            }
            return msg.toString();
        }
        return null;
    }

}
